<script>
import axios from 'axios'
import echarts from 'echarts'

const Tabs = (h, vm) => {
  const tabPanesEl = []
  const tabPanesArr = [
    { label: '水位曲线图', name: 'echart' },
    { label: '闸站信息', name: 'info' },
    { label: '非工程措施', name: 'measures' }
  ]

  tabPanesArr.map(item => {
    tabPanesEl.push(
      h('TabPane', {
        props: item
      })
    )
  })

  return h('div', { class: 'GykjMap-gate-tabs' }, [
    h('Tabs', {
      props: {
        type: 'card',
        animated: false,
        value: vm.activeTab
      },
      on: {
        'input': (value) => {
          vm.activeTab = value
        }
      }
    }, tabPanesEl)
  ])
}

const Echart = (h, vm) => {
  const renderContent = [
    h('div', { class: vm.showEchart ? 'GykjMap-gate-echartData' : 'GykjMap-gate-echartData hide', ref: 'echart' }),
    h('div', { class: vm.showEchart ? 'GykjMap-gate-echartNodata hide' : 'GykjMap-gate-echartNodata' })
  ]

  return h('div', {
    class: vm.activeTab === 'echart' ? 'GykjMap-gate-echart' : 'GykjMap-gate-echart hide'
  }, [renderContent])
}

const Info = (h, vm) => {
  const gateEl = []
  const gateInfo = [
    {
      title: '实时数据',
      table: [
        [
          { title: '水闸名称', key: 'sluicegate_name', keyAttrs: { colspan: 3 } }
        ],
        [
          { title: '外江水位', key: 'water_river_out', isReal: true },
          { title: '内江水位', key: 'water_river_in', isReal: true }
        ],
        [
          { title: '外江趋势', key: 'outertrend', isReal: true },
          { title: '内江趋势', key: 'innertrend', isReal: true }
        ],
        [
          { title: '水泵状态', key: 'pumpstatus', isReal: true },
          { title: '闸门状态', key: 'gatestatus', isReal: true }
        ],
        [
          { title: '数据时间', key: 'data_time', keyAttrs: { colspan: 3 }, isReal: true }
        ]
      ]
    },
    {
      title: '基础数据',
      table: [
        [
          { title: '类型', key: 'statypename', keyAttrs: { colspan: 3 } }
        ],
        [
          { title: '闸长', key: 'dateroom_length', isReal: true },
          { title: '涵闸底板高程（m）', key: 'board_height', isReal: true }
        ],
        [
          { title: '内江极值', key: 'innerriverlimit' },
          { title: '内江警戒值', key: 'innerriverwarn' }
        ],
        [
          { title: '外江极值', key: 'outerriverlimit' },
          { title: '外江警戒值', key: 'outerriverwarn' }
        ],
        [
          { title: '河流', key: 'river' },
          { title: '所在街镇', key: 'town' }
        ],
        [
          { title: '所在堤围', key: 'dick_name' },
          { title: '堤围桩号', key: 'stake_no' }
        ],
        [
          { title: '所在河流', key: 'river' },
          { title: '闸名', key: 'sluicegate_name' }
        ],
        [
          { title: '闸门数', key: 'gatenum' },
          { title: '突变水位', key: 'mutation' }
        ],
        [
          { title: '泵数', key: 'pumpnum' },
          { title: '闸站编号', key: 'stainfoid' }
        ],
        [
          { title: '闸站状态', key: 'stastatus' },
          { title: '审核人', key: 'checkby' }
        ],
        [
          { title: '常态内江警戒水位', key: 'normal_alarm_level_in' },
          { title: '常态外江警戒水位', key: 'normal_alarm_level_out' }
        ],
        [
          { title: '常态内江超限水位', key: 'normal_over_level_in' },
          { title: '常态外江超限水位', key: 'normal_over_level_out' }
        ],
        [
          { title: '排水内江警戒水位', key: 'drain_alarm_level_in' },
          { title: '排水外江警戒水位', key: 'drain_alarm_level_out' }
        ],
        [
          { title: '排水内江超限水位', key: 'drain_over_level_in' },
          { title: '排水外江超限水位', key: 'drain_over_level_out' }
        ],
        [
          { title: '主管部门', key: 'governor' },
          { title: '使用年限', key: 'durable_years' }
        ],
        [
          { title: '信息化设备', key: 'information_equipment' },
          { title: '其他相关预案', key: 'other_plan' }
        ],
        [
          { title: '受影响人员数（人）', key: 'affected_population' },
          { title: '地址', key: 'location' }
        ],
        [
          { title: '工程等级', key: 'project_level' },
          { title: '建设时间', key: 'build' }
        ],
        [
          { title: '工程分类', key: 'project_type' },
          { title: '历史最大过闸流量（m³/s）', key: 'history_flow' }
        ],
        [
          { title: '设计洪水标准（重现期）', key: 'design_flood' },
          { title: '设计流量（m³/s）', key: 'design_flow' }
        ],
        [
          { title: '校核洪水标准（重现期）', key: 'check_flood' },
          { title: '校核流量（m³/s）', key: 'check_flow' }
        ],
        [
          { title: '排涝区面积（m²）', key: 'drain_area' },
          { title: '独立/联合负责排涝区', key: 'drain_region' }
        ],
        [
          { title: '群众转移方案是否编制', key: 'have_tranfer_plan' },
          { title: '联系电话', key: 'contact' }
        ],
        [
          { title: '设计标准', key: 'design_standard' },
          { title: '防洪预案是否编制', key: 'have_emergency_plan' }
        ],
        [
          { title: '历史最高水位', key: 'hightest_depth' },
          { title: '历史最高水位发生时间(年、月、日)', key: 'hightest_time' }
        ],
        [
          { title: '建设(重建)(加固)时间', key: 'rebuild_time' },
          { title: '设计流量(m3/s)', key: 'flow' }
        ],
        [
          { title: '设计启闭水头差(米)', key: 'waterhead' },
          { title: '闸门形式及材料', key: 'gate_material' }
        ],
        [
          { title: '闸门启闭形式', key: 'gate_form' },
          { title: '闸底板高程(m)', key: 'board_height' }
        ],
        [
          { title: '孔数(个)', key: 'holes' },
          { title: '每孔净宽(m)', key: 'hole_width' }
        ],
        [
          { title: '孔高 (米)', key: 'hole_height' },
          { title: '闸室总长(m)', key: 'gateroom_length' }
        ],
        [
          { title: '船室净宽(m)', key: 'shiproom_width' },
          { title: '船室总长(m)', key: 'shiproom_length' }
        ],
        [
          { title: '捍卫面积(亩)', key: 'defence_area' },
          { title: '涵闸类型', key: 'sluicegate_type' }
        ],
        [
          { title: '纬度', key: 'lat' },
          { title: '经度', key: 'lng' }
        ],
        [
          { title: '设计闸前水位（m）', key: 'design_gatebefore_level' },
          { title: '设计闸后水位（m）', key: 'design_gateafter_level' }
        ],
        [
          { title: '校核闸前水位（m）', key: 'check_gatebefore_level' },
          { title: '校核闸后水位（m）', key: 'check_gateafter_level' }
        ],
        [
          { title: '通航能力（吨）', key: 'navigation_capacity', keyAttrs: { colspan: '3' } }
        ],
        [
          { title: '备注', key: 'note', keyAttrs: { colspan: '3' } }
        ]
      ]
    }
  ]

  gateInfo.map(detailItem => {
    const { title, table } = detailItem
    const trEl = []
    table.map(trItem => {
      const td = []

      trItem.map(tdItem => {
        let content = ''
        const { keyAttrs, isReal } = tdItem

        if (isReal) {
          content = vm.fliterRealData(tdItem.key)
        } else {
          content = vm.fliterData(tdItem.key)
        }
        td.push(h('td', {}, tdItem.title))
        td.push(h('td', { attrs: keyAttrs }, content))
      })

      trEl.push(
        h('tr', {}, td)
      )
    })

    const realEl = [
      BaseTitle(h, title),
      h('table', { class: 'GykjMap-table', attrs: { border: true } }, [
        h('tbody', {}, trEl)
      ])
    ]
    const detail = h('div', { class: 'GykjMap-gate-InfoDetail' }, realEl)
    gateEl.push(detail)
  })

  return h('div', { class: vm.activeTab === 'info' ? 'GykjMap-gate-info' : 'GykjMap-gate-info hide' }, gateEl)
}

const Measures = (h, vm) => {
  const safeArr = [
    BaseTitle(h, '安全综合评价'),
    h('table', { class: 'GykjMap-table', attrs: { border: true } }, [
      h('tbody', {}, [
        h('tr', {}, [
          h('td', { attrs: { rowspan: 3 } }, '安全综合评价'),
          h('td', {}, '是否进行过安全综合评价'),
          h('td', { attrs: { colspan: 4 } }, vm.fliterDouData('"sefety_evaluation."be_checked'))
        ]),
        h('tr', {}, [
          h('td', {}, '时间'),
          h('td', { attrs: { colspan: 2 } }, '主要结论'),
          h('td', { attrs: { colspan: 2 } }, '安全类别')
        ]),
        h('tr', {}, [
          h('td', {}, vm.fliterDouData('"sefety_evaluation."heck_date')),
          h('td', { attrs: { colspan: 2 } }, vm.fliterDouData('"sefety_evaluation."result')),
          h('td', { attrs: { colspan: 2 } }, vm.fliterDouData('"sefety_evaluation."safety_type'))
        ])
      ])
    ])
  ]

  const blameTr = []
  const blameArr = [
    { title: '姓名', key1: 'administrator.name', key2: 'technical_director.name', key3: 'operator.name' },
    { title: '单位', key1: 'administrator.department', key2: 'technical_director.department', key3: 'operator.department' },
    { title: '职务', key1: 'administrator.duty', key2: 'technical_director.duty', key3: 'operator.duty' },
    { title: '电话', key1: 'administrator.telephone', key2: 'technical_director.telephone', key3: 'operator.telephone' }
  ]

  blameArr.map(item => {
    blameTr.push(
      h('tr', {}, [
        h('td', {}, item.title),
        h('td', {}, vm.fliterDouData(item.key1)),
        h('td', {}, vm.fliterDouData(item.key2)),
        h('td', {}, vm.fliterDouData(item.key3))
      ])
    )
  })

  const blameEl = [
    BaseTitle(h, '防汛责任制'),
    h('table', { class: 'GykjMap-table', attrs: { border: true } }, [
      h('tbody', {}, [h('tr', {}, [
        h('td', {}),
        h('td', {}, '防汛行政责任人'),
        h('td', {}, '防汛技术责任人'),
        h('td', {}, '管理单位负责人')
      ]), ...blameTr])
    ])
  ]
  const dangerEl = [
    BaseTitle(h, '应急抢险'),
    h('table', { class: 'GykjMap-table GykjMap-center', attrs: { border: true } }, [
      h('tbody', {}, [
        h('tr', {}, [
          h('td', { attrs: { rowspan: 3 } }, '抢险队伍'),
          h('td', { attrs: { rowspan: 2 } }, '人数（人）'),
          h('td', { attrs: { colspan: 2 } }, '负责人'),
          h('td', { attrs: { colspan: 2 } }, '联系人')
        ]),
        h('tr', {}, [
          h('td', { attrs: {} }, '姓名'),
          h('td', { attrs: {} }, '电话'),
          h('td', { attrs: {} }, '姓名'),
          h('td', { attrs: {} }, '电话')
        ]),
        h('tr', {}, [
          h('td', {}, vm.fliterDouData('emergency_team.headcount')),
          h('td', {}, vm.fliterDouData('emergency_team.director')),
          h('td', {}, vm.fliterDouData('emergency_team.director_telephone')),
          h('td', {}, vm.fliterDouData('emergency_team.contacts')),
          h('td', {}, vm.fliterDouData('emergency_team.contact_number'))
        ]),
        h('tr', {}, [
          h('td', { attrs: { rowspan: 3 } }, '防汛抢险物资储备现状情况'),
          h('td', {}, '袋类（条）'),
          h('td', {}, '土工布(m²)'),
          h('td', {}, '砂石(m³)'),
          h('td', {}, '块石(m³)'),
          h('td', {}, '救生衣(件)')
        ]),
        h('tr', {}, [
          h('td', {}, vm.fliterDouData('warehouse_statistics.bag')),
          h('td', {}, vm.fliterDouData('warehouse_statistics.cloth')),
          h('td', {}, vm.fliterDouData('warehouse_statistics.sand')),
          h('td', {}, vm.fliterDouData('warehouse_statistics.block_stone')),
          h('td', {}, vm.fliterDouData('warehouse_statistics.life_jacket'))
        ]),
        h('tr', {}, [
          h('td', {}, '存放点与工程距离(m)'),
          h('td', { attrs: { colspan: 4 } }, vm.fliterDouData('warehouse_statistics.distance'))
        ])
      ])
    ])
  ]

  return h('div', {
    class: vm.activeTab === 'measures' ? 'GykjMap-gate-measures' : 'GykjMap-criticals-measures hide'
  }, [
    h('div', { class: 'GykjMap-gate-measuresDetail' }, safeArr),
    h('div', { class: 'GykjMap-gate-measuresDetail' }, blameEl),
    h('div', { class: 'GykjMap-gate-measuresDetail' }, dangerEl)
  ])
}

const Content = (h, vm) => {
  return h('div', { class: 'GykjMap-gate-content' }, [
    Echart(h, vm),
    Info(h, vm),
    Measures(h, vm)
  ])
}

const Wrapper = (h, vm) => {
  return h('div', { class: 'GykjMap-gate-warpper' }, [
    Tabs(h, vm),
    Content(h, vm)
  ])
}

const BaseTitle = (h, title) => {
  return h('div', { class: 'GykjMap-baseTitle' }, [
    h('div', { class: 'GykjMap-baseTitle-wrapper' }, [
      h('div', { class: 'GykjMap-baseTitle-decorate' }),
      h('div', { class: 'GykjMap-baseTitle-content' }, title)
    ])
  ])
}

const Loading = (h, vm) => {
  const divArr = []
  for (let index = 0; index < 8; index++) {
    divArr.push(h('div', {}))
  }

  return h('div', { class: vm.loading ? 'GykjMap-loading-box' : 'GykjMap-loading-box hide' }, [
    h('div', { class: 'GykjMap-loading-wrapper' }, [
      h('div', { class: 'GykjMap-loading-content' }, [
        h('div', { class: 'loader' }, [
          h('div', { class: 'loader-inner ball-spin-fade-loader' }, divArr)
        ])
      ]),
      h('div', { class: 'GykjMap-loading-title' }, '加载中')
    ])
  ])
}

const echartExample = (data) => ({
  title: {
    text: '实时水位趋势',
    x: 'center',
    top: 20
  },
  grid: {
    left: 70
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: data.x
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} m'
    }
  },
  series: [{
    name: '内江',
    type: 'line',
    data: data.inner
  }, {
    name: '外江',
    type: 'line',
    data: data.outer
  }]
})

export default {
  props: {
    stnNo: {
      type: String,
      default: ''
    },
    source: {
      type: String,
      default: ''
    },
    isInit: {
      type: Boolean,
      default: true
    }
  },
  mounted () {
    if (this.isInit) {
      this.initData()
    }
  },
  data () {
    return {
      resultData: {},
      activeTab: 'measures',
      showEchart: false,
      loading: false
    }
  },
  render (h) {
    return h('div', {
      class: 'GykjMap-gate'
    }, [
      Wrapper(h, this),
      Loading(h, this)
    ])
  },
  methods: {
    initData (stnNo, data = {}) {
      this.resultData = data
      this.showEchart = false
      this.activeTab = 'echart'
      this.api = 'http://183.238.82.216:9080/fullservice/http/waterDataReal'

      if (stnNo) {
        this.api += `?stn_no=${stnNo}`
      } else {
        if (this.source) {
          this.api = this.source
        } else if (!this.source && this.stnNo) {
          this.api += `?stn_no=${this.stnNo}`
        } else {
          return
          // throw new Error('必须传入api源地址或水闸编号')
        }
      }

      this.getData()
    },
    getData () {
      this.loading = true

      axios.get(this.api, {})
        .then(res => {
          this.loading = false
          const data = res.data

          if (data.code === '0000' && data.result.length) {
            const time = []
            const inner = []
            const outer = []
            const info = data.result.reverse()

            info.map(item => {
              let str = item.data_time
              str = str.split(' ').join('\n')
              time.push(str)
              inner.push(item.water_river_in)
              outer.push(item.water_river_out)
            })

            const echartData = {
              x: time,
              inner: inner,
              outer: outer
            }

            this.initEchart(echartData)
          } else {
            this.$emit('data_err', '找不到该水闸的实时数据')
            console.log('找不到该水闸的实时数据')
          }
        })
        .catch(err => {
          this.loading = false
          this.$emit('data_err', `获取该数据源失败，错误代码：${err}`)
          console.log(`获取该数据源失败，错误代码：${err}`)
        })
    },
    initEchart (data) {
      if (!data) {
        return
      }

      this.showEchart = true
      setTimeout(() => {
        if (!this.echart) {
          this.echart = echarts.init(this.$refs.echart)
        }
        this.echart.setOption(echartExample(data))
      }, 20)
    },
    fliterData (key) {
      if (this.resultData[key] === 0) {
        return this.resultData[key]
      }
      return this.resultData[key] || '--'
    },
    fliterDouData (key) {
      const arr = key.split('.')

      if (this.resultData[arr[0]] === undefined) {
        this.resultData[arr[0]] = {}
      }

      return this.resultData[arr[0]][arr[1]] || '--'
    },
    fliterRealData (key) {
      return this.resultData.realtime_data ? this.resultData.realtime_data[key] || this.resultData.realtime_data[key] === 0 ? this.resultData.realtime_data[key] : '--' : '--'
    }
  }
}
</script>

<style lang="scss" scoped>
.GykjMap-gate {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .GykjMap-gate-warpper {
    width: 100%;
    height: 100%;
    .GykjMap-gate-tabs {
      width: 100%;
      height: 42px;
      overflow: hidden;
      padding: 5px;
    }
    .GykjMap-gate-content {
      width: 100%;
      height: calc(100% - 37px);
      position: relative;
      overflow: hidden;
      .GykjMap-gate-echart {
        width: 100%;
        height: 100%;
        margin: auto;
        overflow: hidden;
        padding: 5px;
        &.hide {
          display: none;
        }
        .GykjMap-gate-echartData {
          width: 100%;
          height: 100%;
          &.hide {
            display: none;
          }
        }
        .GykjMap-gate-echartNodata {
          width: 100%;
          height: 100%;
          text-align: center;
          background-image: url("./img/noCount.png");
          background-position: center 35%;
          background-repeat: no-repeat;
          &.hide {
            display: none;
          }
        }
      }
      .GykjMap-gate-info {
        width: 100%;
        height: 100%;
        padding: 5px;
        overflow-y: auto;
        &.hide {
          display: none;
        }
        .GykjMap-table {
          width: 100%;
          font-size: 14px;
          border: 1px solid #ddd;
          margin-bottom: 5px;
          td {
            width: 25%;
            padding: 5px;
          }
        }
      }
      .GykjMap-gate-measures {
        width: 100%;
        height: 100%;
        padding: 5px;
        overflow-y: auto;
        &.hide {
          display: none;
        }
        .GykjMap-gate-measuresDetail {
          margin-bottom: 10px;
          .GykjMap-table {
            width: 100%;
            font-size: 14px;
            border: 1px solid #ddd;
            margin-bottom: 5px;
            &.GykjMap-center {
              text-align: center;
            }
            td {
              padding: 5px;
            }
          }
        }
      }
    }
  }

  .GykjMap-baseTitle {
    width: 100%;
    margin-bottom: 5px;
    .GykjMap-baseTitle-wrapper {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      .GykjMap-baseTitle-decorate {
        width: 6px;
        height: 24px;
        margin-right: 10px;
        border-radius: 0 4px 4px 0;
        background-color: #008cee;
      }
      .GykjMap-baseTitle-content {
        flex: 1;
        font-size: 14px;
      }
    }
  }

  .GykjMap-loading-box {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 9999;
    user-select: none;
    &.hide {
      display: none;
    }
    .GykjMap-loading-wrapper {
      width: 80px;
      height: 80px;
      padding: 10px 0;
      background-color: rgba(0, 0, 0, .6);
      border-radius: 5px;
      position: absolute;
      box-sizing: border-box;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
      color: white;
      text-align: center;
      .GykjMap-loading-content {
        width: 100%;
        text-align: center;
        .loader {
          width: 100%;
          height: 100%;
          box-sizing: border-box;
          display: flex;
          flex: 0 1 auto;
          flex-direction: column;
          flex-grow: 1;
          flex-shrink: 0;
          flex-basis: 25%;
          align-items: center;
          justify-content: center;
          position: absolute;
          left: 0;
          right: 0;
          top: -10px;
          margin: auto;
          transform: scale(0.35);
        }
        @-webkit-keyframes ball-spin-fade-loader {
          50% {
              opacity: 0.3;
              -webkit-transform: scale(0.4);
              transform: scale(0.4);
          }
          100% {
              opacity: 1;
              -webkit-transform: scale(1);
              transform: scale(1);
          }
        }
        @keyframes ball-spin-fade-loader {
          50% {
              opacity: 0.3;
              -webkit-transform: scale(0.4);
              transform: scale(0.4);
          }
          100% {
              opacity: 1;
              -webkit-transform: scale(1);
              transform: scale(1);
          }
        }
        .ball-spin-fade-loader {
          position: relative;
        }
        .ball-spin-fade-loader > div:nth-child(1) {
          top: 32px;
          left: -12px;
          -webkit-animation: ball-spin-fade-loader 1s 0s infinite linear;
          animation: ball-spin-fade-loader 1s 0s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(2) {
          top: 17.04545px;
          left: 17.04545px;
          -webkit-animation: ball-spin-fade-loader 1s 0.12s infinite linear;
          animation: ball-spin-fade-loader 1s 0.12s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(3) {
          top: -12px;
          left: 32px;
          -webkit-animation: ball-spin-fade-loader 1s 0.24s infinite linear;
          animation: ball-spin-fade-loader 1s 0.24s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(4) {
          top: -40.04545px;
          left: 17.04545px;
          -webkit-animation: ball-spin-fade-loader 1s 0.36s infinite linear;
          animation: ball-spin-fade-loader 1s 0.36s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(5) {
          top: -52px;
          left: -12px;
          -webkit-animation: ball-spin-fade-loader 1s 0.48s infinite linear;
          animation: ball-spin-fade-loader 1s 0.48s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(6) {
          top: -40.04545px;
          left: -40.04545px;
          -webkit-animation: ball-spin-fade-loader 1s 0.6s infinite linear;
          animation: ball-spin-fade-loader 1s 0.6s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(7) {
          top: -12px;
          left: -52px;
          -webkit-animation: ball-spin-fade-loader 1s 0.72s infinite linear;
          animation: ball-spin-fade-loader 1s 0.72s infinite linear;
        }
        .ball-spin-fade-loader > div:nth-child(8) {
          top: 17.04545px;
          left: -40.04545px;
          -webkit-animation: ball-spin-fade-loader 1s 0.84s infinite linear;
          animation: ball-spin-fade-loader 1s 0.84s infinite linear;
        }
        .ball-spin-fade-loader > div {
          background-color: #fff;
          width: 15px;
          height: 15px;
          border-radius: 100%;
          margin: 2px;
          -webkit-animation-fill-mode: both;
          animation-fill-mode: both;
          position: absolute;
        }
      }
      .GykjMap-loading-title {
        width: 100%;
        position: absolute;
        bottom: 2px;
        text-align: center;
        padding: 5px;
        box-sizing: border-box;
      }
    }
  }
}
</style>
